package com.wis.bolt.risk;

import com.alibaba.fastjson.JSONObject;
import com.wis.tools.CommonUtiles;
import com.wis.tools.RiskUtiles;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.List;
import java.util.Map;

/**
 * @Description: traffic_fan    生成风险告警信息
 * @author: fan
 * @Date: Created in 2018/10/30 15:15
 * @Modified By:
 */
public class RiskLineDataBolt extends BaseRichBolt {
    private OutputCollector collector = null;
    private static RiskUtiles utils = new RiskUtiles();
    private JSONObject jsonPoint;
    private JSONObject jsonContent;
    private static int count;

    @Override
    public void prepare(Map map, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
        count = 1;
        jsonPoint = new CommonUtiles().getHttpJsonObject(map.get("queryID").toString());
        jsonContent = new CommonUtiles().getHttpJsonObject(map.get("queryRiskInfo").toString());
    }

    @Override
    public void execute(Tuple tuple) {
        // 道路预警列表中的详情内容按此规则：“高速编号”“高速名称”“省份”“县/区”“桩号”-“桩号”段，“天气信息”。如“G1京哈高速吉林省扶余县K717-K751段，当前有降雪，未来30分钟能见度低于100米”。
        String key = tuple.getStringByField("key");
        String value = tuple.getStringByField("value");
        try {
            if (StringUtils.isNotBlank(value) && !value.contains("over")) {
                // 开始桩点id，结束桩点id，相态，指标等级
                List list = utils.getRiskLineInfo(key, value, jsonPoint, jsonContent);
                // System.out.println("风险告警信息：" + StringUtils.join(list, ","));
                this.collector.emit(new Values(key, StringUtils.join(list, ",")));
            } else if (value.contains("over")) {
                count++;
                if (count == 5) {
                    this.collector.emit(new Values(key, "over"));
                    count = 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }
}
